import router from '.'
import store from '@/store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'
import pubsub from 'pubsub-js'

function findDefaultPath(defaultPath){
  if(Array.isArray(defaultPath)){
    return findDefaultPath(defaultPath[0])
  }else if(typeof defaultPath === 'object' && defaultPath.hasOwnProperty('children')){
    return '/' + defaultPath.path + findDefaultPath(defaultPath.children)
  }else{
    return defaultPath ? '/' + defaultPath.path : '/'
  }
}

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect', '/binding', '/bind', '/register', '/404']

router.beforeEach(async(to,from,next)=>{
  NProgress.start()
  const hasToken = getToken()
  //! try语句块中throw出可以强制logout
  try {
    if (hasToken) {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      const hasPermission = store.getters.permissions && store.getters.permissions.length > 0
      if (hasRoles) {
        //! 第二步：根据userType分配路径
        //此时无权限用户roles:['ROLE_DEFAULT'],permissions:[]

          if(to.path==='/login'){
            next('/')
            NProgress.done()
          }else if(to.path==='/defaultPath'){
            if(hasPermission){
              const defaultPath = findDefaultPath(store.getters.add_routes).slice(1)
              next(defaultPath)
            }else{
              pubsub.publish('handleNoPermission', 'noPermission')
              NProgress.done()
              throw new Error('此账号未分配权限！')
            }
          } else{
            next()
          }

      }else{
        //! 第一步：获取权限
        const { roles,user } = await store.dispatch('GetInfo')
        const accessRoutes = await store.dispatch('GenerateRoutes', roles)
        console.log('外',accessRoutes);
        router.addRoutes(accessRoutes)
        if(user.isItCertified === '0' || user.isItCertified === '1' || user.isItCertified === '2' || user.isItCertified === '6'){
          next({ path: 'approve' })
        }else{
          next({ ...to, replace: true })
        }
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        next()
      }else{
        next(`/login`)
        NProgress.done()
      }
    }
  }catch(error){
    //登出
    await store.dispatch('LogOut')
    // Message.error(error || 'Has Error')
    next(`/login`)
    NProgress.done()
  }
})

// router.beforeEach((to, from, next) => {
//   // debugger
//   NProgress.start()
//   if(to.path == '/index' && to.query.redirect != 'system') {
//     //首页跳转官网
//     next({path:'webHome', replace:true})
//   } else if(to.path.indexOf('webHome') > -1) {
//     //首页跳转官网页面
//     next()
//   } else if (getToken()) {
//     //已登录系统
//     to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
//     /* has token*/
//     if (store.getters.roles.length === 0) {
//       isRelogin.show = true
//       // 判断当前用户是否已拉取完user_info信息
//       store.dispatch('GetInfo').then((res) => {
//         isRelogin.show = false
//         const user = res.user
//         //绑定企业状态 -1:已删除 0:未提交 1:待审核 2:驳回 3:审核通过 4:冻结 5:无须认证 6:未绑定
//         if (user.isItCertified === '0' || user.isItCertified === '1' || user.isItCertified === '2' || user.isItCertified === '6') {
//           next({ path: 'approve' })
//         } else {
//           store.dispatch('GenerateRoutes').then(accessRoutes => {
//             // debugger
//             // 根据roles权限生成可访问的路由表
//             //router.addRoutes(accessRoutes) // 动态添加可访问路由表
//             if(to.path == '/login' || (to.path == '/index' || to.path == '/') && to.query && to.query.redirect == 'system') {
//               if(accessRoutes.length == 0) {
//                 store.dispatch('LogOut').then(() => {
//                   next({path:'404'})
//                 })
//               } else {
//                 const path = goSystemDefaultPage[user.userType]
//                 next({path:path, replace:true})
//               }
//             } else {
//               next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
//             }
//           })
//         }
//       }).catch(err => {
//           store.dispatch('LogOut').then(() => {
//             Message.error(err)
//             next({ path: '/login' })
//           })
//         })
//     } else {
//       next()
//     }
//   } else if(whiteList.indexOf(to.path) !== -1) {
//     next()
//   } else {
//      // 没有token
//     next('/login') // 否则全部重定向到登录页
//   }

// })

router.afterEach(() => {
  NProgress.done()
})
